package com.example.servlet.user;

import com.example.entity.User;
import com.example.service.ManagerService;
import com.example.service.UserService;
import com.example.service.impl.ManagerServiceImpl;
import com.example.service.impl.UserServiceImpl;
import com.example.utils.BCryptUtil;
import com.example.utils.MybatisUtil;
import com.example.utils.ThymeleafUtil;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.IOException;

@WebServlet("/user_account_manage")
public class uAccountManageServlet extends HttpServlet {
    private UserService service;
    private SqlSession sqlSession;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        sqlSession = MybatisUtil.getSession();
        service = new UserServiceImpl(sqlSession);
    }

    @Override
    public void destroy() {
        sqlSession.close();
        super.destroy();
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User) req.getSession().getAttribute("user");
        Context context = new Context();
        context.setVariable("user", user);
        if (req.getSession().getAttribute("password_same") != null) {
            context.setVariable("password_same", true);
            req.getSession().removeAttribute("password_same");
        }
        if (req.getSession().getAttribute("password_wrong") != null) {
            context.setVariable("password_wrong", true);
            req.getSession().removeAttribute("password_wrong");
        }
        if (req.getSession().getAttribute("current_password_wrong") != null) {
            context.setVariable("current_password_wrong", true);
            req.getSession().removeAttribute("current_password_wrong");
        }
        if (req.getSession().getAttribute("update_success") != null) {
            context.setVariable("update_success", true);
            req.getSession().removeAttribute("update_success");
        }
        if (req.getSession().getAttribute("update_failure") != null) {
            context.setVariable("update_failure", true);
            req.getSession().removeAttribute("update_failure");
        }
        if (req.getSession().getAttribute("unsubscribe_failure") != null) {
            context.setVariable("unsubscribe_failure", true);
            req.getSession().removeAttribute("unsubscribe_failure");
        }
        if (req.getSession().getAttribute("password_error") != null) {
            context.setVariable("password_error", true);
            req.getSession().removeAttribute("password_error");
        }
        if (user.getEmail() == null || user.getEmail().isEmpty()) {
            context.setVariable("email", "null");
        }
        // 图片是否存在判断
        String imagePath = getServletContext().getRealPath("/static/images/" + user.getU_id() + ".jpg");
        File imageFile = new File(imagePath);
        boolean imageExists = imageFile.exists();
        context.setVariable("imageExists", imageExists);
        context.setVariable("unsubscribe_error", "password_empty");
        ThymeleafUtil.process("user_account_manage.html", context, resp.getWriter());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User) req.getSession().getAttribute("user");
        String current_password = req.getParameter("current_password");
        String new_password = req.getParameter("new_password");
        String confirm_password = req.getParameter("confirm_password");
        try{
            if(current_password.equals(new_password)){
                req.getSession().setAttribute("password_same", new Object());
                this.doGet(req, resp);
            }else{
                if (new_password.equals(confirm_password)) {
                    String storedHashedPassword = service.getHashedPasswordByAccount(user.getU_account());
                    if (storedHashedPassword != null) {
                        // 使用 BCryptUtil 验证密码
                        boolean isPasswordCorrect = BCryptUtil.verifyPassword(current_password, storedHashedPassword);
                        if (isPasswordCorrect) {
                            String hashedPassword = BCryptUtil.encryptPassword(new_password); // 加密密码
                            if(service.updatePassword(hashedPassword, user.getU_account()) == 0){
                                throw new Exception("Failed to update user");
                            }
                            service.commit();
                            req.getSession().setAttribute("update_success", new Object());
                            this.doGet(req, resp);
                        }else{
                            req.getSession().setAttribute("current_password_wrong", new Object());
                            this.doGet(req, resp);
                        }
                    }
                }else{
                    req.getSession().setAttribute("password_wrong", new Object());
                    this.doGet(req, resp);
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            // 回滚事务
            service.rollback();
            req.getSession().setAttribute("update_failure", new Object());
            this.doGet(req, resp);
        }
    }
}
